//
//  SIOperationViewController.m
//  CampingLight
//
//  Created by Piccolo on 2017/11/10.
//  Copyright © 2017年 SmartIT. All rights reserved.
//

#import "SIOperationViewController.h"
#import "SIMyDeviceViewController.h"
#import "SIAutoReportInfo.h"
#import "CampingLight-Swift.h"
#include <math.h>
#import <mach/mach.h>

#define kMinDate [SIUtil getFiveTimesDateFromDate:[NSDate date]]

@interface SIOperationViewController () <TenClockDelegate, ASValueTrackingSliderDelegate> {
    CustomizationState _state;
    CGFloat _currentCircleBarValue;
    NSArray *_hourArray;
    NSArray *_minuteArray;
    SIAutoReportInfo *_lightAutoReportInfo;
    NSTimer *_timer;
    DGActivityIndicatorView *_indicator;
    NSSILightMode _currentMode;

    BOOL _needUpdateSoundSwich;
    BOOL _isSliding;
    TenClock *_clock;
    NSDate *_startDate;
    NSDate *_endDate;
    BOOL _needDetectTouch;
    BOOL _needUpdateProgress;
    BOOL _needUpdateAwakenClock;
    CGFloat _angleBuffer;
    NSInteger _beyondMinOrMaxType;
    NSInteger _ignoreFirstBuffer;
    
    BOOL _controlViewEnabled;
    BOOL _awakenViewEnabled;
    BOOL _smartViewEnabled;
    
    BOOL _lightIsOn;
}

@end

@implementation SIOperationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupInitialization];
    [self setupViewControllerBackGroundColor];
    [self setupNaviBar];
    [self setupControlView];
    [self setupAwakenView];
    [self setupBottomView];
    [self setupSmartView];
    [self adaptDevice];
    [self updateDisplayView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self updateProgressBarValueAndProgressBarBtn];
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
//    [self setupLightTypeView];
}

- (void)setupInitialization {
    _bottomControlBtn.tag = 1;
    _needDetectTouch = NO;
    _needUpdateProgress = YES;
    _needUpdateAwakenClock = NO;
}

- (void)adaptDevice {
    if ([SIUtil checkPlatformIsFiveType] || [SIUtil checkPlatformIsFourType]) {
        [SIUtil setCustomView:self.view transformMakeWidth:320.f / 375.f height:1136.f / 1334.f];
    }
}

- (void)setupControlView {
    [self setupControlInitialization];
    [self setupSuperBtn];
    [self setupMinusBtnAndPlusBtn];
    [self setupCircleProgressBar];
    [self setupSlider];
    [self setupLightTypeView];
    [self setupControlSwitch];
}

- (void)setupAwakenView {
    [self setupAwakenTopView];
    [self setupAwakenTimerView];
    [self setupAwakenTimerSelectView];
}

- (void)setupSmartView {
    [self setupSmartTopView];
    [self setupSmartOperateTimerBtn];
    [self setupCountDownView];
    [self setupSmartDatePickerView];
}

- (void)setupBottomView {
    [SIUtil setBtn:_bottomOnOffBtn
                imageName:nil
          needRoundCorner:YES
                   target:self
                   action:@selector(bottomOnOffBtnOnClick:)];
    [SIUtil setBtn:_bottomControlBtn
                imageName:nil
          needRoundCorner:YES
                   target:self
                   action:@selector(bottomControlBtnOnClick:)];
    [SIUtil setBtn:_bottomAwakenBtn
                imageName:nil
          needRoundCorner:YES
                   target:self
                   action:@selector(bottomAwakenBtnOnClick:)];
    [SIUtil setBtn:_bottomSmartBtn
                imageName:nil
          needRoundCorner:YES
                   target:self
                   action:@selector(bottomSmartBtnOnClick:)];
    
    _onOffLabel.text = [SIUtil getSingleKeyStr:@"TEXT_ON_OFF"];
    _bottomControlLabel.text = [SIUtil getSingleKeyStr:@"TEXT_CONTROL"];
    _bottomAwakenLabel.text = [SIUtil getSingleKeyStr:@"TEXT_AWAKEN"];
    _bottomSmartLabel.text = [SIUtil getSingleKeyStr:@"TEXT_SMART"];
}

- (void)updateDisplayView {
    
    _controlView.hidden = !_bottomControlBtn.tag;
    _awakenView.hidden = !_bottomAwakenBtn.tag;
    _smartView.hidden = !_bottomSmartBtn.tag;
    
    if (!_controlView.hidden) {
        self.navigationItem.title = [SIUtil getSingleKeyStr:@"TEXT_CONTROL_CENTER"];
    } else if (!_awakenView.hidden) {
        self.navigationItem.title = [SIUtil getSingleKeyStr:@"TEXT_AWAKEN_CENTER"];
    } else if (!_smartView.hidden) {
        self.navigationItem.title = [SIUtil getSingleKeyStr:@"TEXT_SMART_CENTER"];
    }
    
    [SIUtil setBtn:_bottomOnOffBtn selected:_bottomOnOffBtn.tag];
    [SIUtil setBtn:_bottomControlBtn selected:_bottomControlBtn.tag];
    [SIUtil setBtn:_bottomAwakenBtn selected:_bottomAwakenBtn.tag];
    [SIUtil setBtn:_bottomSmartBtn selected:_bottomSmartBtn.tag];

    [SIUtil setBtn:_bottomOnOffBtn enabled:_controlViewEnabled];
    [SIUtil setBtn:_bottomControlBtn enabled:YES];
    [SIUtil setBtn:_bottomAwakenBtn enabled:YES];
    [SIUtil setBtn:_bottomSmartBtn enabled:YES];
}

- (void)bottomOnOffBtnOnClick:(UIButton *)btn {
    
    SILightInfo *lightInfo = [_lightAutoReportInfo.lightInfo copy];
    if (!btn.tag) {
        if (_currentCircleBarValue == 0 || lightInfo.mode == NSSILightModeOff) {
            
            SILightInfo *currentLightInfo = [_lightAutoReportInfo.lightInfo copy];
            SILightInfo *resultLightInfo = [SIUtil lightInfoFromSceneType:NSSISceneTypeSceneCurrent currentLightInfo:currentLightInfo];
            if (!resultLightInfo.brightnessValue) {
                resultLightInfo = [SIUtil lightInfoFromSceneType:NSSISceneTypeSleeping currentLightInfo:currentLightInfo];
            }
            resultLightInfo.mode = NSSILightModeDimming;
            [SICPSDKService sendSettingBasicInfoFromLightInfo:resultLightInfo];
        }
        
    } else {
        [self turnOffLight];
    }
//    [_delegate didSendRequest];
//    [self updateControlView];
    
}

- (void)bottomControlBtnOnClick:(UIButton *)btn {
    if (!btn.tag) {
        btn.tag = 1;
        _bottomAwakenBtn.tag = 0;
        _bottomSmartBtn.tag = 0;
        [self updateDisplayView];
    }
}

- (void)bottomAwakenBtnOnClick:(UIButton *)btn {
    if (!btn.tag) {
        btn.tag = 1;
        _bottomControlBtn.tag = 0;
        _bottomSmartBtn.tag = 0;
        [self updateDisplayView];
    }
}

- (void)bottomSmartBtnOnClick:(UIButton *)btn {
    if (!btn.tag) {
        btn.tag = 1;
        _bottomControlBtn.tag = 0;
        _bottomAwakenBtn.tag = 0;
        [self updateDisplayView];
    }
}


/*-- Control View --*/

- (void)setupControlInitialization {
    _currentCircleBarValue = 0;
}

- (void)setupViewControllerBackGroundColor {
    if ([SIUtil checkPlatformIsFiveType] || [SIUtil checkPlatformIsFourType]) {
        [SIUtil resetView:(UIView *)_controlView deltaX:0 deltaY:12.f deltaWidth:0 deltaHeight:-12.f];
        [SIUtil resetView:(UIView *)_awakenView deltaX:0 deltaY:12.f deltaWidth:0 deltaHeight:-12.f];
        [SIUtil resetView:(UIView *)_smartView deltaX:0 deltaY:12.f deltaWidth:0 deltaHeight:-12.f];
    }
    _controlView.backgroundColor = LIGHT_GRAY_COLOR_WITH_ALPHA_5;
    _awakenView.backgroundColor = LIGHT_GRAY_COLOR_WITH_ALPHA_5;
    _smartView.backgroundColor = LIGHT_GRAY_COLOR_WITH_ALPHA_5;
}



- (void)setupLightTypeView {
    [self setRoundCornerBtn:_controlIndicatorLightBtn];
    [self setRoundCornerBtn:_controlSoundBtn];
    [SIUtil setSuperView:_controlSwitchView fromLastSubView:_controlIndicatorLightBtn spacing:16.f];
}

- (void)setupControlSwitch {
    
    [SIUtil setDownView:_controlIndicatorLightBtn aboveView:_controlSoundBtn spacing:8.f];
    _controlIndicatorSwitch.center = CGPointMake(_controlIndicatorSwitch.center.x, _controlIndicatorLightBtn.center.y);
    [_controlIndicatorSwitch addTarget:self action:@selector(indicatorSwitchToggled:) forControlEvents:UIControlEventValueChanged];
    _controlSoundSwitch.center = CGPointMake(_controlSoundSwitch.center.x, _controlSoundBtn.center.y);
    [_controlSoundSwitch addTarget:self action:@selector(soundSwitchToggled:) forControlEvents: UIControlEventValueChanged];
}

- (void)indicatorSwitchToggled:(UISwitch *)indicatorSwitch {
    
    SILightAddtionalInfo *lightAddtionalInfo = [_lightAutoReportInfo.lightInfo.lightAddtionalInfo copy];
    lightAddtionalInfo.lightIndicatorStatus = indicatorSwitch.on ? 1 : 0;
    [SICPSDKService sendAdditionalCommandFromLightAddtionalInfo:lightAddtionalInfo];
}

- (void)soundSwitchToggled:(UISwitch *)soundSwitch {

    SILightAddtionalInfo *lightAddtionalInfo = [_lightAutoReportInfo.lightInfo.lightAddtionalInfo copy];
    lightAddtionalInfo.lightSoundStatus = soundSwitch.on ? 1 : 0;
    [SICPSDKService sendAdditionalCommandFromLightAddtionalInfo:lightAddtionalInfo];
    _needUpdateSoundSwich = YES;
}

- (void)setRoundCornerBtn:(UIButton *)btn {
    [SIUtil setViewRoundCorner:btn];
//    CGPoint midPoint = CGPointMake(CGRectGetMidX(btn.frame), CGRectGetMidY(btn.frame));
//    [btn si_setWidth:CGRectGetHeight(_awakenSwitch.frame)];
//    [btn si_setHeight:CGRectGetHeight(_awakenSwitch.frame)];
//    btn.center = midPoint;
    btn.layer.borderWidth = 0;
}

- (void)setupNaviBar {
    self.navigationItem.title = [SIUtil getSingleKeyStr:@"TEXT_CONTROL_CENTER"];
    UIBarButtonItem *backItem = [SIUtil newBarItemWithImageName:@"ico-back.png" target:self action:@selector(backBtnOnClick:)];
    self.navigationItem.leftBarButtonItem = backItem;
}

- (void)setupSuperBtn {
    [SIUtil setBtn:_controlSuperBtn imageName:nil needRoundCorner:YES target:self action:@selector(controlSuperBtnOnClick:)];
    _controlSuperBtn.layer.borderColor = [UIColor clearColor].CGColor;
    [_controlSuperBtn setTitle:[SIUtil getSingleKeyStr:@"TEXT_SUPER"] forState:UIControlStateNormal];
}

- (void)updateProgressBarValueAndProgressBarBtn {
    
    BOOL progressBarEnabled = _bottomOnOffBtn.tag && _controlViewEnabled;
    _controlCircleProgressBar.enabled = progressBarEnabled;
    _controlProgressBarValueLabel.textColor = progressBarEnabled ? SMARTIT_MAIN_COLOR : [UIColor lightGrayColor];
//    NSString *dishImageName = progressBarEnabled ? @"表盘-刻度.png" : @"表盘刻度-灰色.png";
    NSString *dishImageName = @"表盘-刻度.png";
    _controlDishImageView.image = [UIImage imageNamed:dishImageName];
    [_controlDishImageView si_setTintColor:progressBarEnabled ? nil : [UIColor lightGrayColor]];
    NSInteger circleBarIntegerValue = 0;
    if (_needUpdateProgress && progressBarEnabled) {
        [_controlCircleProgressBar setProgress:_currentCircleBarValue == 0 ? .01f : _currentCircleBarValue animated:YES];
        circleBarIntegerValue = [self circleDisplayIntegerValueFromProgressBarFloatValue:_currentCircleBarValue];

        _controlProgressBarValueLabel.text = [NSString stringWithFormat:@"%ld", circleBarIntegerValue];
        _controlProgressBarValueLabel.font = [UIFont fontWithName:_controlProgressBarValueLabel.font.fontName size:[self getFontSizeWithInt:_currentCircleBarValue * 100.f]];
        _controlMinusBtn.enabled = _currentCircleBarValue > 0;
        _controlPlusBtn.enabled = _currentCircleBarValue < 1;
    } else if (!progressBarEnabled) {
        //_controlCircleProgressBar.progress
        [_controlCircleProgressBar setProgress:_controlCircleProgressBar.progress == 0 ? .01f : _controlCircleProgressBar.progress animated:YES];
        _currentCircleBarValue = 0;
        circleBarIntegerValue = [self circleDisplayIntegerValueFromProgressBarFloatValue:_controlCircleProgressBar.progress];
        _controlProgressBarValueLabel.text = [NSString stringWithFormat:@"%ld", circleBarIntegerValue];
        _controlProgressBarValueLabel.font = [UIFont fontWithName:_controlProgressBarValueLabel.font.fontName size:[self getFontSizeWithInt:_controlCircleProgressBar.progress * 100.f]];
        
        _controlPlusBtn.enabled = NO;
        _controlMinusBtn.enabled = NO;
        
    }

}
- (NSInteger)circleDisplayIntegerValueFromProgressBarFloatValue:(CGFloat)floatValue {
    NSInteger circleBarIntegerValue = (NSInteger)(floatValue * 100.f);
    if ((circleBarIntegerValue + 1) % 5 == 0) {
        circleBarIntegerValue ++;
    } else if ((circleBarIntegerValue - 1) % 5 == 0) {
        circleBarIntegerValue --;
    }
    return circleBarIntegerValue;
}

- (void)updateMinusBtnAndPlusBtnEnabled {
    _controlMinusBtn.enabled = _currentCircleBarValue > 0;
    _controlPlusBtn.enabled = _currentCircleBarValue < 1;
}

- (void)setupMinusBtnAndPlusBtn {
    [SIUtil setBtn:_controlMinusBtn imageName:@"left.png" needRoundCorner:NO target:self action:@selector(controlMinusBtnOnClick:)];
    [SIUtil setBtn:_controlPlusBtn imageName:@"right.png" needRoundCorner:NO target:self action:@selector(controlPlusBtnOnClick:)];
}

#pragma mark - set circle start
- (void)customizeAccordingToState:(CustomizationState)state {
    BOOL customized = YES;
    // Progress Bar Customization
    [_controlCircleProgressBar setProgressBarWidth:15.f];
    [_controlCircleProgressBar setProgressBarProgressColor:(customized ? [UIColor colorWithRed:0.0 green:1 blue:0.0 alpha:1.f] : nil)];
    [_controlCircleProgressBar setProgressBarTrackColor:(customized ? [UIColor colorWithWhite:0.000 alpha:0.000] : nil)];
}

- (CGFloat)getFontSizeWithInt:(NSInteger)index{
    if (index < 10) {
        
        return 80.f;
    }
    else if (index >= 10 && index < 100){
        return 70.f;
    }
    else if (index >= 100){
        return 65.f;
    }
    return 0;
}

- (void)setupCircleProgressBar {
    [_controlCircleProgressBar setStartAngle: -90.f];
    _state = CustomizationStateCustom;
    [self customizeAccordingToState:_state];
    _controlProgressBarValueLabel.textAlignment = NSTextAlignmentCenter;
}

- (void)setupSlider {
    // customize slider 2
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterPercentStyle];
    [_controlSlider setNumberFormatter:formatter];
    _controlSlider.font = [UIFont fontWithName:@"Futura-CondensedExtraBold" size:26];
    _controlSlider.popUpViewAnimatedColors = @[GRADIENT_START_COLOR, GRADIENT_MIDDLE_COLOR, GRADIENT_END_COLOR];
    _controlSlider.popUpViewArrowLength = 20.0;
    _controlSlider.delegate = self;
}

- (void)backBtnOnClick:(UIButton *)btn {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)controlMinusBtnOnClick:(UIButton *)btn {
    
    btn.enabled = NO;
    NSInteger lightBrightnessValue = [self currentBrightnessValue] - 5;
    if (lightBrightnessValue < 0) {
        lightBrightnessValue = 0;
    }
    SILightInfo *lightInfo = [_lightAutoReportInfo.lightInfo copy];
    lightInfo.brightnessValue = lightBrightnessValue;
    [SICPSDKService sendSettingBasicInfoFromLightInfo:lightInfo];
    [_delegate didSendRequest];
    [self updateControlView];
    
}

- (void)controlPlusBtnOnClick:(UIButton *)btn {
    
    btn.enabled = NO;
    NSInteger lightBrightnessValue = [self currentBrightnessValue] + 5;
    if (lightBrightnessValue > 100) {
        lightBrightnessValue = 100;
    }
    SILightInfo *lightInfo = [_lightAutoReportInfo.lightInfo copy];
    lightInfo.brightnessValue = lightBrightnessValue;
    [SICPSDKService sendSettingBasicInfoFromLightInfo:lightInfo];
}

- (void)controlSuperBtnOnClick:(UIButton *)btn {
    
}

- (void)updateBottomOnOffBtn {
    [SIUtil setBtn:_bottomOnOffBtn enabled:YES];
    _bottomOnOffBtn.tag = _lightIsOn ? 1 : 0;
}

- (NSInteger)currentBrightnessValue {
    return _lightAutoReportInfo.lightInfo.brightnessValue;
}

- (NSInteger)currentColorTempValue {
    return _lightAutoReportInfo.lightInfo.colorTempValue;
}

- (void)updatePrograss {
    _currentCircleBarValue = [self currentBrightnessValue] / 100.f;
    [self updateProgressBarValueAndProgressBarBtn];
}

- (void)updateSliderImageView {
    UIColor *resultColor = _bottomOnOffBtn.tag ? [UIColor whiteColor] : [UIColor lightGrayColor];
    [_hotImageView si_setTintColor:resultColor];
    [_coldImageView si_setTintColor:resultColor];
//    _controlDishImageView si_setTintColor:<#(UIColor *)#>
}

- (void)updateSlider {
    _controlSlider.enabled = _bottomOnOffBtn.tag && _controlViewEnabled;
    if (_controlSlider.enabled && !_isSliding) {
        _controlSlider.value = [self currentColorTempValue] / 100.f;
    } else {
        
    }
}


#pragma mark - ASValueTrackingSliderDelegate

- (void)sliderWillDisplayPopUpView:(ASValueTrackingSlider *)slider {
    _isSliding = YES;
}

- (void)sliderWillHidePopUpView:(ASValueTrackingSlider *)slider {
    
    NSInteger colorTempValue = slider.value * 100.f;
    SILightInfo *lightInfo = [_lightAutoReportInfo.lightInfo copy];
    [SIUtil setCampingLightInfo:lightInfo brightnessValue:lightInfo.brightnessValue colorTempValue:colorTempValue];
    [SICPSDKService sendSettingBasicInfoFromLightInfo:lightInfo];
    //        [_delegate didSendRequest];
    [self startTimer];
}

- (void)sliderDidHidePopUpView:(ASValueTrackingSlider *)slider {
    _isSliding = NO;
}

- (void)updateBattery {
    
    NSInteger index = 0;
    NSString *imageName = @"";

    if (_lightAutoReportInfo.lightBatteryStatus == NSSIBatteryStatusTypeCharging) {
        imageName = @"power_charging.png";
        
    } else {
        NSInteger battery = _lightAutoReportInfo.lightBattery;
        if (battery <= 10) {
            index = 0;
        } else if (battery <= 30) {
            index = 1;
        } else if (battery <= 50) {
            index = 2;
        } else if (battery <= 70) {
            index = 3;
        } else if (battery <= 90) {
            index = 4;
        } else if (battery <= 100) {
            index = 5;
        }
        imageName = [NSString stringWithFormat:@"power%ld.png", index];
    }
    
    _batteryImageView.image = [UIImage imageNamed:imageName];

}

- (void)updateSoundSwitchView {
    _controlSoundSwitch.on = _lightAutoReportInfo.lightInfo.lightAddtionalInfo.lightSoundStatus;
}

- (void)updateIndicatorSwitchView {
    _controlIndicatorSwitch.on = _lightAutoReportInfo.lightInfo.lightAddtionalInfo.lightIndicatorStatus;
}


- (void)updateControlView {

    [self updateBottomOnOffBtn];
    [self updatePrograss];
    [self updateSlider];
    [self updateSliderImageView];
    [self updateBattery];
    [self saveCurrentScene];
    [self updateSoundSwitchView];
    [self updateIndicatorSwitchView];
//    NSLog(@"@408 point:%@", NSStringFromCGPoint([self progressBarPoint]));
}

- (void)saveCurrentScene {
    if (![SIUtil checkCampingLightInfo:[_lightAutoReportInfo.lightInfo copy] isType:NSSISceneTypeSceneCurrent]) {
        if (_lightAutoReportInfo.lightInfo.brightnessValue) {
            [SIUtil setUserDefaultCampingLightInfo:[_lightAutoReportInfo.lightInfo copy] toSceneType:NSSISceneTypeSceneCurrent];
        }
    }
}

//当有一个或多个手指触摸事件在当前视图或window窗体中响应
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (_bottomOnOffBtn.tag) {
        NSSet *allTouches = [event allTouches];    //返回与当前接收者有关的所有的触摸对象
        UITouch *touch = [allTouches anyObject];   //视图中的所有对象
        CGPoint point = [touch locationInView:_controlTopView]; //返回触摸点在视图中的当前坐标
        CGFloat x = point.x;
        CGFloat y = point.y;
        CGPoint progressBarPoint = [self progressBarPoint];
        
        if (fabs(x - progressBarPoint.x) <= 50 && fabs(y - progressBarPoint.y) <= 50) {
            _needDetectTouch = YES;
            _needUpdateProgress = NO;
            _ignoreFirstBuffer = NO;
        }
        
        NSLog(@"@415touch (x, y) is (%f, %f)", x, y);
        NSLog(@"@416top view center:%@", NSStringFromCGPoint(_controlCircleProgressBar.center));
    }
    
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event {
    if (_needDetectTouch) {
        
        
        if (_ignoreFirstBuffer) {
            NSSet *allTouches = [event allTouches];    //返回与当前接收者有关的所有的触摸对象
            UITouch *touch = [allTouches anyObject];   //视图中的所有对象
            CGPoint point = [touch locationInView:_controlTopView]; //返回触摸点在视图中的当前坐标
            CGFloat x = point.x;
            CGFloat y = point.y;
            CGFloat angle = [self angleFromTouchMovingPoint:point];
            if (angle > 1.98 * M_PI) {
                //            progressBarValue = 1;
                angle = 2 * M_PI;
            } else if (angle < .01f * 2 * M_PI) {
                //            progressBarValue = 0;
                angle = 0;
            }
            
            BOOL leftMoving = NO;
            if (angle - _angleBuffer > 5.f / 3.f * M_PI) {
                leftMoving = YES;
            } else if (angle - _angleBuffer < -5.f / 3.f * M_PI) {
                leftMoving = NO;
            } else {
                leftMoving = angle < _angleBuffer;
            }
            BOOL rightMoving = !leftMoving;//_angleBuffer - angle > 5.f / 3.f * M_PI ? YES : angle > _angleBuffer;
            if (angle == _angleBuffer) {
                return;
            }
//            if (leftMoving) {
//                NSLog(@"@495LEFT");
//            }
//            if (rightMoving) {
//                NSLog(@"@495RIGHT");
//            }
//            if (angle == 2 * M_PI || angle == 0) {
//                NSLog(@"@502");
//            }
            BOOL isMinProgressValueAndLeftMoving = angle < .01f * 2 * M_PI && leftMoving;
            BOOL isMinProgressValueAndRightMoving = angle > 1.98 * M_PI && rightMoving;
            
//            NSLog(@"@424moved (x, y) is (%f, %f)", x, y);
//            NSLog(@"@416top view center:%@", NSStringFromCGPoint(_controlCircleProgressBar.center));
            CGFloat progressBarValue = angle / 2 / M_PI;
            
//            NSLog(@"@513,angle:%f ", angle);
            
            if (_beyondMinOrMaxType == 0) {
                
                if (x > CGRectGetWidth(_controlTopView.frame) ||
                    y > CGRectGetHeight(_controlTopView.frame) ||
                    isMinProgressValueAndLeftMoving ||
                    isMinProgressValueAndRightMoving) {
                    if (isMinProgressValueAndLeftMoving) {
                        NSLog(@"@527 left 禁锢开始");
                        
                        _beyondMinOrMaxType = -1;
                    } else if (isMinProgressValueAndRightMoving) {
                        NSLog(@"@527 right 禁锢开始");
                        
                        _beyondMinOrMaxType = 1;
                    }
                }
                [_controlCircleProgressBar setProgress:progressBarValue < .01 ? .01f : progressBarValue animated:YES];
                int brightnessValue = (int)(progressBarValue * 100);
                _controlProgressBarValueLabel.text = [NSString stringWithFormat:@"%d", brightnessValue];
                
                
            } else if (_beyondMinOrMaxType == -1) {
//                if (angle < 2.f * M_PI / 50.f && angle > 0) {
                if (rightMoving && x > _controlCircleProgressBar.center.x && y < _controlCircleProgressBar.center.y) {
                    
                    NSLog(@"@527 left 禁锢解除");
                    _beyondMinOrMaxType = 0;
                }
            } else if (_beyondMinOrMaxType == 1) {
//                if (angle > M_PI && angle < 2 * M_PI) {
                if (leftMoving && x < _controlCircleProgressBar.center.x && y < _controlCircleProgressBar.center.y) {
                    NSLog(@"@527 right 禁锢解除");
                    
                    _beyondMinOrMaxType = 0;
                }
            }
            _angleBuffer = angle;
        }
        
        _ignoreFirstBuffer = YES;
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (_needDetectTouch) {
        _needUpdateProgress = YES;
        NSSet *allTouches = [event allTouches];    //返回与当前接收者有关的所有的触摸对象
        UITouch *touch = [allTouches anyObject];   //视图中的所有对象
        CGPoint point = [touch locationInView:_controlTopView]; //返回触摸点在视图中的当前坐标
        CGFloat angle = [self angleFromTouchMovingPoint:point];
        CGFloat progressBarValue = angle / 2 / M_PI;
        int brightnessValue = (int)(progressBarValue * 100);
        
        if (_beyondMinOrMaxType == -1) {
            brightnessValue = 1;
        } else if (_beyondMinOrMaxType == 1) {
            brightnessValue = 100;
        }
        
        SILightInfo *lightInfo = [_lightAutoReportInfo.lightInfo copy];
        [SIUtil setCampingLightInfo:lightInfo brightnessValue:brightnessValue colorTempValue:lightInfo.colorTempValue];
        [SICPSDKService sendSettingBasicInfoFromLightInfo:lightInfo];
//        [_delegate didSendRequest];
        [self startTimer];
//        [self updateControlView];
        
        _needDetectTouch = NO;

    }
}

- (CGPoint)progressBarPoint {
    CGFloat radius = CGRectGetWidth(_controlCircleProgressBar.frame) / 2.f;
    CGFloat value = _controlCircleProgressBar.progress;
    CGPoint progressBarCenterPoint = _controlCircleProgressBar.center;
    CGFloat angle = value * M_PI * 2;
    CGFloat xValue = 0;
    CGFloat yValue = 0;
    CGPoint targetPoint = CGPointMake(0, 0);
    CGFloat tempAngle = 0;
    if (angle >= 0 && angle <= M_PI_2) {
        tempAngle = angle;
        xValue = radius * sinf(tempAngle);
        yValue = radius * cosf(tempAngle);
        targetPoint = CGPointMake(progressBarCenterPoint.x + xValue, progressBarCenterPoint.y - yValue);
    } else if (angle <= M_PI) {
        tempAngle = angle - M_PI_2;
        xValue = radius * cosf(tempAngle);
        yValue = radius * sinf(tempAngle);
        targetPoint = CGPointMake(progressBarCenterPoint.x + xValue, progressBarCenterPoint.y + yValue);
    } else if (angle <= M_PI_2 * 3) {
        tempAngle = angle - M_PI;
        xValue = radius * sinf(tempAngle);
        yValue = radius * cosf(tempAngle);
        targetPoint = CGPointMake(progressBarCenterPoint.x - xValue, progressBarCenterPoint.y + yValue);
    } else if (angle <= M_PI_2 * 4) {
        tempAngle = angle - M_PI_2 * 3;
        xValue = radius * cosf(tempAngle);
        yValue = radius * sinf(tempAngle);
        targetPoint = CGPointMake(progressBarCenterPoint.x - xValue, progressBarCenterPoint.y - yValue);
    }
    return targetPoint;
}

- (CGFloat)angleFromTouchMovingPoint:(CGPoint)point {
    CGPoint topViewCenterPoint = _controlTopView.center;
    CGFloat xValue = point.x - topViewCenterPoint.x;
    CGFloat yValue = point.y - topViewCenterPoint.y;
    CGFloat angle = 0;
    if (xValue == 0 && yValue < 0) {
        angle = 0;
    } else if (xValue > 0 && yValue < 0) {
        angle = atanf(xValue / -yValue);
    } else if (xValue > 0 && yValue == 0) {
        angle = M_PI_2;
    } else if (xValue > 0 && yValue > 0) {
        angle = atanf(yValue / xValue) + M_PI_2;
    } else if (xValue == 0 && yValue > 0) {
        angle = M_PI;
    } else if (xValue < 0 && yValue > 0) {
        angle = atanf(-xValue / yValue) + M_PI;
    } else if (xValue < 0 && yValue == 0) {
        angle = M_PI_2 * 3;
    } else if (xValue < 0 && yValue < 0) {
        angle = atanf(-yValue / -xValue) + M_PI_2 * 3;
    } else if (xValue == 0 && yValue == 0) {
        angle = 0;
    }
    return angle;
}




/*-- Awaken View --*/

- (void)setupAwakenTopView {
    _awakenTopView.backgroundColor = LIGHT_GRAY_COLOR_WITH_ALPHA_10;
    _awakenTopViewLabel.text = [SIUtil getSingleKeyStr:@"TEXT_AWAKEN"];
    [_awakenSwitch addTarget:self action:@selector(awakenSwitchToggled:) forControlEvents: UIControlEventValueChanged];

}


- (void)setupAwakenTimerView {
    _awakenOnLabel.text =[SIUtil getSingleKeyStr:@"TEXT_ON"];
    _awakenOffLabel.text =[SIUtil getSingleKeyStr:@"TEXT_OFF"];
    if (_lightAutoReportInfo.lightInfo.lightAddtionalInfo.lightAwakenStatus) {
        SILightInfo *currentLightInfo = [_lightAutoReportInfo.lightInfo copy];
        _startDate = [SIUtil awakenOnTimeFromCampingLightInfo:currentLightInfo];
        _endDate = [SIUtil awakenOffTimeFromCampingLightInfo:currentLightInfo];
    } else {
        _startDate = _startDate ? _startDate : kMinDate;
        _endDate = _endDate ? _endDate : [SIUtil getDateAfterDate:_startDate day:0 hour:8 minute:0 second:0];
    }
}

- (void)setupAwakenTimerSelectView {
    [self setupClock];
}

- (void)setupClock {
    //    TenClockDelegat
    _needUpdateAwakenClock = YES;
    CGFloat awakenTimeSelectViewWidth = CGRectGetWidth(_awakenTimeSelectView.frame);
    if (DEVICE_VERSION >= 11) {
        awakenTimeSelectViewWidth *= SCREEN_WIDTH_COEFFIENT;
    }
    _clock = [[TenClock alloc] initWithFrame:CGRectMake(0, 0, awakenTimeSelectViewWidth, awakenTimeSelectViewWidth)];
    [_awakenTimeSelectView addSubview:_clock];
    [self updateStartTimeAndEndTime];
    _clock.startDate = _startDate;
    _clock.endDate = _endDate;
    _clock.pathWidth = 40.f;
    _clock.delegate = self;
    [_clock update];
}

- (void)updateStartTimeAndEndTime {
    if (_lightAutoReportInfo.lightInfo.lightAddtionalInfo.lightAwakenStatus) {
        SILightInfo *currentLightInfo = [_lightAutoReportInfo.lightInfo copy];
        _startDate = [SIUtil awakenOnTimeFromCampingLightInfo:currentLightInfo];
        _endDate = [SIUtil awakenOffTimeFromCampingLightInfo:currentLightInfo];
//        _startDate = [SIUtil getDateAfterDay:0 hour:0 minute:onTime second:0];
//        _endDate = [SIUtil getDateAfterDay:0 hour:0 minute:onTime - offTime second:0];
    } else {
        _startDate = _startDate ? _startDate : kMinDate;
        _endDate = _endDate ? _endDate : [SIUtil getDateAfterDate:_startDate day:0 hour:8 minute:0 second:0];
    }
}

- (void)awakenSwitchToggled:(UISwitch *)awakenSwitch {
//    [self updateAwakenViewWithEnabled:awakenSwitch.on];
//    _bottomAwakenBtn.tag = awakenSwitch.on ? 1 : 0;
    if (awakenSwitch.on) {
        [self updateAwakenInfoFromStartTime:_startDate endtime:_endDate lightAwakenStatus:NSSIEnableStatusOn];
        
    } else {
        [self updateAwakenInfoFromStartTime:_startDate endtime:_endDate lightAwakenStatus:NSSIEnableStatusOff];
        [self turnOffLight];
    }
//    [self updateAwakenView];
}

- (void)updateAwakenInfoFromStartTime:(NSDate *)startTime endtime:(NSDate *)endTime lightAwakenStatus:(NSSIEnableStatus)lightAwakenStatus {

    _needUpdateAwakenClock = YES;
    SILightInfo *currentLightInfo = [_lightAutoReportInfo.lightInfo copy];
    currentLightInfo.lightTimeInfo.awakenOnTimeHour = [SIUtil hourFromTime:startTime];
    currentLightInfo.lightTimeInfo.awakenOnTimeMinute = [SIUtil minuteFromTime:startTime];
    currentLightInfo.lightTimeInfo.awakenOffTimeHour = [SIUtil hourFromTime:endTime];
    currentLightInfo.lightTimeInfo.awakenOffTimeMinute = [SIUtil minuteFromTime:endTime];
    currentLightInfo.lightAddtionalInfo.lightAwakenStatus = lightAwakenStatus;
    [SICPSDKService sendSettingAwakenInfoFromLightInfo:currentLightInfo];
    [_delegate didSendRequest];
}

- (void)turnOffLight {
    SILightInfo *currentLightInfo = [_lightAutoReportInfo.lightInfo copy];
    [SIUtil setCampingLightInfo:currentLightInfo mode:NSSILightModeOff];
    [SICPSDKService sendSettingBasicInfoFromLightInfo:currentLightInfo];
}

- (void)updateAwakenView {
    
    BOOL enabled = _awakenViewEnabled;
    _awakenSwitch.on = !enabled;
    _clock.disabled = !enabled;
    //_needUpdateAwakenClock
    if (YES) {
        
        _awakenOnLabel.textColor = enabled ? SMARTIT_MAIN_COLOR : [UIColor lightGrayColor];
        _awakenOffLabel.textColor = enabled ? SMARTIT_MAIN_COLOR : [UIColor lightGrayColor];
        _awakenOnTimerLabel.textColor = enabled ? [UIColor whiteColor] : [UIColor lightGrayColor];
        _awakenOffTimerLabel.textColor = enabled ? [UIColor whiteColor] : [UIColor lightGrayColor];
        
        [_awakenOnImageView si_setTintColor:enabled ? SMARTIT_MAIN_COLOR : [UIColor lightGrayColor]];
        [_awakenOffImageView si_setTintColor:enabled ? SMARTIT_MAIN_COLOR : [UIColor lightGrayColor] ];
//        _awakenOnImageView.image = enabled ? [UIImage imageNamed:@"ico- 15.png"] : [UIImage imageNamed:@"ring_disabled.png"];
//        _awakenOffImageView.image = enabled ? [UIImage imageNamed:@"ico- 16.png"] : [UIImage imageNamed:@"moon_disabled.png"];
        
        //new 1.21
//        _startDate = _lightAutoReportInfo.lightInfo.onTime;
//        _endDate = _lightAutoReportInfo.lightInfo.offTime;
        
        if (!_awakenViewEnabled) {
            [self updateAwakenTimeSelectLabelFromStartTime:_startDate endTime:_endDate];
            [self updateStartTimeAndEndTime];
            NSLog(@"@%@:%@", _startDate, _endDate);
    
            _clock.startDate = _startDate;
            _clock.endDate = _endDate;
            [_clock update];
        }
        
//        _needUpdateAwakenClock = NO;
    }
}

- (void)updateAwakenTimeSelectLabelFromStartTime:(NSDate *)startTime endTime:(NSDate *)endTime {
//    NSDate *startDate = _lightAutoReportInfo.lightInfo.onTime;
//    NSDate *endDate = _lightAutoReportInfo.lightInfo.offTime;
    _awakenOnTimerLabel.text = [SIUtil convertDateToString:startTime withFormatter:SI_HOUR_MINUTE_TIME_FORMATTER];
    _awakenOffTimerLabel.text = [SIUtil convertDateToString:endTime withFormatter:SI_HOUR_MINUTE_TIME_FORMATTER];
}


#pragma mark - TenClockDelegate

- (void)timesUpdated:(TenClock *)clock startDate:(NSDate *)startDate endDate:(NSDate *)endDate {
    
    //实时更新
    _clock.startDate = startDate;
    _clock.endDate = endDate;
    _needUpdateAwakenClock = NO;
    [self updateAwakenTimeSelectLabelFromStartTime:startDate endTime:endDate];
    [_clock update];
}

- (void)timesChanged:(TenClock *)clock startDate:(NSDate *)startDate endDate:(NSDate *)endDate {
    
    //放开更新

    if (fabs([startDate timeIntervalSinceDate:endDate]) <= 30 * 60) {
        endDate = [SIUtil getDateAfterDate:startDate day:0 hour:0 minute:30 second:0];
        _clock.endDate = endDate;
        [_clock update];
    }
    _startDate = startDate;
    _endDate = endDate;
    [self updateAwakenTimeSelectLabelFromStartTime:startDate endTime:endDate];
    [self startTimer];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
//        _needUpdateAwakenClock = YES;
    });
    NSLog(@"@8199 start : %@  end : %@", startDate, endDate);

}


/*-- Smart View --*/

- (void)setupSmartTopView {
    _smartTopView.backgroundColor = LIGHT_GRAY_COLOR_WITH_ALPHA_10;
    _smartTopViewLabel.text = [SIUtil getSingleKeyStr:@"TEXT_SMART_LIGHT"];
}

- (void)setupSmartOperateTimerBtn {

    [SIUtil setBtn:_smartCancelBtn imageName:@"取消180@2x.png" title:[SIUtil getSingleKeyStr:@"TEXT_CANCEL"] target:self action:@selector(cancelBtnOnClick:)];
    _smartCancelBtn.imageEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
    [SIUtil setBtn:_smartOperationalBtn imageName:@"开始180@2x.png" title:[SIUtil getSingleKeyStr:@"TEXT_START"] target:self action:@selector(startBtnOnClick:)];
    _smartOperationalBtn.imageEdgeInsets = UIEdgeInsetsMake(-5, -5, -5, -5);
}

- (void)setupCountDownView {
    
}

- (void)updateCountDownView {
    
//    NSInteger deltaTimeInterval = [_lightAutoReportInfo.lightInfo.offTime timeIntervalSinceNow];
//    if (deltaTimeInterval < 0) {
//        deltaTimeInterval += kSecondOfDay;
//    }
    NSInteger hour = _lightAutoReportInfo.lightInfo.lightTimeInfo.smartTimeHour;
    NSInteger minute = _lightAutoReportInfo.lightInfo.lightTimeInfo.smartTimeMinute;
    NSInteger second = _lightAutoReportInfo.lightInfo.lightTimeInfo.smartTimeSecond;
    
//    NSInteger hour = deltaTimeInterval / kSecondOfHour;
//    NSInteger minute = deltaTimeInterval % kSecondOfHour / 60;
//
//    //防止越界
//    if (minute == 59) {
//        minute = 0;
//        hour ++;
//    } else {
//        minute ++;
//    }
//    if (hour == 24) {
//        hour = 0;
//    }
    
    NSString *hourStr = hour < 10 ? [NSString stringWithFormat:@"0%ld", hour] : [NSString stringWithFormat:@"%ld", hour];
    NSString *minuteStr = minute < 10 ? [NSString stringWithFormat:@"0%ld", minute] : [NSString stringWithFormat:@"%ld", minute];
    NSString *secondStr = second < 10 ? [NSString stringWithFormat:@"0%ld", second] : [NSString stringWithFormat:@"%ld", second];
    
    _smartCountDownTimeLabel.text = [NSString stringWithFormat:@"%@:%@:%@", hourStr, minuteStr, secondStr];
}


- (void)setupSmartDatePickerView {
    _smartTimePickerView.datePickerMode = UIDatePickerModeCountDownTimer;
    [_smartTimePickerView setValue:RGB_UICOLOR(48, 191, 161) forKey:@"textColor"];
    
//    self.datePicker.datePickerMode = UIDatePickerModeDate;
//    [self.datePicker setValue:[UIColor colorWithRed:70/255.0f green:161/255.0f blue:174/255.0f alpha:1.0f] forKeyPath:@"textColor"];
    
    if ([_smartTimePickerView respondsToSelector:sel_registerName("setHighlightsToday:")]) {
        
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
        
        [_smartTimePickerView performSelector:@selector(setHighlightsToday:) withObject:[NSNumber numberWithBool:NO]];
        
#pragma clang diagnostic pop
        
    }
    
//    [_smartTimePickerView setValue:[UIColor whiteColor] forKey:@"textColor"];
}

- (void)updateSmartView {
    
    _smartCountDownView.hidden = !_smartViewEnabled;
    _smartSelectTimeView.hidden = _smartViewEnabled;
    
    [self updateSmartViewBtn];
    [self updateCountDownView];
}

- (void)updateSmartViewBtn {
    _smartOperationalBtn.enabled = !_smartSelectTimeView.hidden;
    if (!_smartViewEnabled) {
//        _smartOperationalBtn.enabled = _lightIsOn;
    }
    _smartCancelBtn.enabled = !_smartCountDownView.hidden;
}

- (void)cancelBtnOnClick:(UIButton *)btn {
    SILightInfo *lightInfo = [_lightAutoReportInfo.lightInfo copy];
    [SIUtil setCampingLightInfo:lightInfo mode:NSSILightModeOff];
    [SIUtil setCampingLightInfo:lightInfo smartTimeHour:0 smartTimeMinute:0];
    [SICPSDKService sendSettingBasicInfoFromLightInfo:lightInfo];
    [_delegate didSendRequest];
}

- (void)startBtnOnClick:(UIButton *)btn {
//    [self updateSmartView];
//    _smartTimePickerView.
    NSLog(@"@333:%@", _smartTimePickerView.date);
    NSInteger hour = [SIUtil hourFromTime:_smartTimePickerView.date];
    NSInteger minute = [SIUtil minuteFromTime:_smartTimePickerView.date];
    if (!hour && !minute) {
        minute = 1;
    }
    
    SILightInfo *lightInfo = [_lightAutoReportInfo.lightInfo copy];
    [SIUtil setCampingLightInfo:lightInfo mode:NSSILightModeSmart];
    [SIUtil setCampingLightInfo:lightInfo smartTimeHour:hour smartTimeMinute:minute];
    [SICPSDKService sendSettingBasicInfoFromLightInfo:lightInfo];
    [_delegate didSendRequest];
    
    
}

- (void)updateOperationViewController {
    
    _currentMode = _lightAutoReportInfo.lightInfo.mode;
    _lightIsOn = _lightAutoReportInfo.lightInfo.brightnessValue > 0 && _currentMode != NSSILightModeOff;
    BOOL isModeOff = _lightAutoReportInfo.lightInfo.mode == NSSILightModeOff;
    _controlViewEnabled = _lightAutoReportInfo.lightInfo.mode == NSSILightModeDimming || isModeOff;
    _awakenViewEnabled = !_lightAutoReportInfo.lightInfo.lightAddtionalInfo.lightAwakenStatus;//_lightAutoReportInfo.lightInfo.mode == NSSILightModeTimer && !isModeOff;
    _smartViewEnabled = _lightAutoReportInfo.lightInfo.mode == NSSILightModeSmart && !isModeOff;
    
    [self updateControlView];
    [self updateDisplayView];
    [self updateSmartView];
    [self updateAwakenView];
//    if (_testMMM < 95092352) {
//        
//    }
    
    
}

#pragma mark - SmartITMyDeviceViewControllerFuntion
- (void)updateAutoReport:(SICPSDKResultInfo *)activeReportInfo {
    if ([SIUtil isExistDic:activeReportInfo.detailDic key:@"auto_basic_report_data"]) {
        _lightAutoReportInfo = [[SIAutoReportInfo alloc] initWithSmartITCampingLightAutoReportInfoData:activeReportInfo.detailDic[@"auto_basic_report_data"]];
    }
    //    if ([SIUtil isExistDic:activeReportInfo.detailDic key:@"auto_current_report_data"]) {
    //        [_lightAutoReportInfo updateWithSmartITCampingLightCurrentReportInfoData:activeReportInfo.detailDic[@"auto_current_report_data"]];
    //        NSLog(@"@这里来了");
    //    }
    //    [self updateOperationViewController];
    
    if (!_timer) {
        [self updateOperationViewController];
    }
    
//    [self report_memory];
}

- (void)bleDisconnect {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)startTimer {
    _timer = nil;
    _timer = [NSTimer new];
    _timer = [NSTimer scheduledTimerWithTimeInterval:3.f target:self selector:@selector(destoryTimer:) userInfo:nil repeats:NO];
}

- (void)destoryTimer:(NSTimer *)timer {
    _timer = nil;
}

//- (void)report_memory {
//    struct task_basic_info info;
//    mach_msg_type_number_t size = sizeof(info);
//    kern_return_t kerr = task_info(mach_task_self(),
//                                   TASK_BASIC_INFO,
//                                   (task_info_t)&info,
//                                   &size);
//    if( kerr == KERN_SUCCESS ) {
//        NSLog(@"Memory in use (in bytes): %lu", info.resident_size);
//        NSLog(@"Memory in use (in MB): %f", ((CGFloat)info.resident_size / 1000000));
////        _testMMM = info.resident_size;
//    } else {
//        NSLog(@"Error with task_info(): %s", mach_error_string(kerr));
//    }
//}
@end
